/**
 * 🎬 视频检测测试页面
 * 用于测试和调试视频文件检测功能
 */

import React, { useState, useEffect } from 'react'
import { detectVideosInPublicFolder } from '../utils/videoDetector'
import type { VideoItem } from '../component/VideoSelector'

export const VideoDetectionTest: React.FC = () => {
  const [detectedVideos, setDetectedVideos] = useState<VideoItem[]>([])
  const [isLoading, setIsLoading] = useState(false)
  const [lastRefresh, setLastRefresh] = useState<string>('')
  const [testResults, setTestResults] = useState<string[]>([])

  // 检测视频
  const detectVideos = async () => {
    setIsLoading(true)
    setTestResults([])
    
    try {
      console.log('🔍 开始检测视频文件...')
      setTestResults(prev => [...prev, '🔍 开始检测视频文件...'])
      
      const videos = await detectVideosInPublicFolder()
      
      console.log(`✅ 检测完成，找到 ${videos.length} 个视频:`, videos)
      setTestResults(prev => [...prev, `✅ 检测完成，找到 ${videos.length} 个视频`])
      
      videos.forEach((video, index) => {
        const msg = `${index + 1}. ${video.name} (${video.size || '未知大小'})`
        console.log(msg)
        setTestResults(prev => [...prev, msg])
      })
      
      setDetectedVideos(videos)
      setLastRefresh(new Date().toLocaleString())
      
    } catch (error) {
      const errorMsg = `❌ 检测失败: ${error instanceof Error ? error.message : '未知错误'}`
      console.error(errorMsg)
      setTestResults(prev => [...prev, errorMsg])
    } finally {
      setIsLoading(false)
    }
  }

  // 测试单个视频文件
  const testVideoFile = async (filename: string) => {
    const url = `/videos/${filename}`
    
    try {
      console.log(`🧪 测试视频文件: ${filename}`)
      setTestResults(prev => [...prev, `🧪 测试视频文件: ${filename}`])
      
      const response = await fetch(url, { method: 'HEAD' })
      
      if (response.ok) {
        const size = response.headers.get('content-length')
        const sizeStr = size ? `${Math.round(parseInt(size) / 1024 / 1024)}MB` : '未知大小'
        const msg = `✅ ${filename} - 可访问 (${sizeStr})`
        console.log(msg)
        setTestResults(prev => [...prev, msg])
      } else {
        const msg = `❌ ${filename} - 无法访问 (${response.status})`
        console.log(msg)
        setTestResults(prev => [...prev, msg])
      }
    } catch (error) {
      const msg = `❌ ${filename} - 网络错误: ${error instanceof Error ? error.message : '未知错误'}`
      console.log(msg)
      setTestResults(prev => [...prev, msg])
    }
  }

  // 批量测试所有已知视频
  const testAllKnownVideos = async () => {
    setIsLoading(true)
    setTestResults([])
    
    const knownVideos = [
      '视频二.mp4',
      '视频一.mp4', 
      '视频三.mp4',
      '4880454-uhd_2160_4096_25fps.mp4',
      '4316251-uhd_2160_3840_30fps.mp4',
      '5362370-uhd_3840_2160_25fps.mp4',
      '3044160-uhd_3840_2160_24fps.mp4',
      '2795750-uhd_3840_2160_25fps.mp4',
      '2795749-uhd_3840_2160_25fps.mp4',
      '2873755-uhd_3840_2160_25fps.mp4'
    ]

    console.log('🧪 开始批量测试视频文件...')
    setTestResults(['🧪 开始批量测试视频文件...'])

    for (const filename of knownVideos) {
      await testVideoFile(filename)
    }

    setIsLoading(false)
  }

  // 页面加载时自动检测
  useEffect(() => {
    detectVideos()
  }, [])

  return (
    <div style={{ 
      padding: '20px', 
      fontFamily: 'monospace',
      backgroundColor: '#f8f9fa',
      minHeight: '100vh'
    }}>
      <h2 style={{ color: '#333', marginBottom: '20px' }}>
        🎬 视频检测测试工具
      </h2>

      {/* 控制按钮 */}
      <div style={{ marginBottom: '20px' }}>
        <button
          onClick={detectVideos}
          disabled={isLoading}
          style={{
            padding: '10px 20px',
            backgroundColor: '#007bff',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            marginRight: '10px',
            cursor: isLoading ? 'not-allowed' : 'pointer',
            opacity: isLoading ? 0.6 : 1
          }}
        >
          {isLoading ? '🔄 检测中...' : '🔍 重新检测视频'}
        </button>

        <button
          onClick={testAllKnownVideos}
          disabled={isLoading}
          style={{
            padding: '10px 20px',
            backgroundColor: '#28a745',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            marginRight: '10px',
            cursor: isLoading ? 'not-allowed' : 'pointer',
            opacity: isLoading ? 0.6 : 1
          }}
        >
          {isLoading ? '🧪 测试中...' : '🧪 测试所有文件'}
        </button>

        <button
          onClick={() => window.location.reload()}
          style={{
            padding: '10px 20px',
            backgroundColor: '#6c757d',
            color: 'white',
            border: 'none',
            borderRadius: '5px',
            cursor: 'pointer'
          }}
        >
          🔄 刷新页面
        </button>
      </div>

      {/* 最后刷新时间 */}
      {lastRefresh && (
        <div style={{ 
          marginBottom: '20px', 
          padding: '10px',
          backgroundColor: '#d4edda',
          border: '1px solid #c3e6cb',
          borderRadius: '5px',
          color: '#155724'
        }}>
          ⏰ 最后检测时间: {lastRefresh}
        </div>
      )}

      {/* 检测到的视频列表 */}
      <div style={{ marginBottom: '20px' }}>
        <h3 style={{ color: '#333' }}>
          📹 检测到的视频 ({detectedVideos.length} 个)
        </h3>
        
        {detectedVideos.length > 0 ? (
          <div style={{
            display: 'grid',
            gridTemplateColumns: 'repeat(auto-fill, minmax(300px, 1fr))',
            gap: '15px'
          }}>
            {detectedVideos.map((video) => (
              <div
                key={video.id}
                style={{
                  padding: '15px',
                  backgroundColor: 'white',
                  border: '1px solid #dee2e6',
                  borderRadius: '8px',
                  boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
                }}
              >
                <div style={{ fontWeight: 'bold', marginBottom: '5px', color: '#333' }}>
                  {video.name}
                </div>
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '5px' }}>
                  ID: {video.id}
                </div>
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '5px' }}>
                  URL: {video.url}
                </div>
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '5px' }}>
                  大小: {video.size || '未知'}
                </div>
                <div style={{ fontSize: '12px', color: '#666' }}>
                  时长: {video.duration || '未知'}
                </div>
                
                {/* 🎭 人物检测支持状态 */}
                <div style={{
                  marginTop: '10px',
                  padding: '5px 10px',
                  backgroundColor: '#d4edda',
                  color: '#155724',
                  borderRadius: '4px',
                  fontSize: '12px',
                  fontWeight: 'bold',
                  textAlign: 'center'
                }}>
                  ✅ 支持人物检测 (本地文件)
                </div>
              </div>
            ))}
          </div>
        ) : (
          <div style={{
            padding: '20px',
            backgroundColor: '#f8d7da',
            border: '1px solid #f5c6cb',
            borderRadius: '5px',
            color: '#721c24',
            textAlign: 'center'
          }}>
            ❌ 没有检测到任何视频文件
          </div>
        )}
      </div>

      {/* 测试日志 */}
      <div>
        <h3 style={{ color: '#333' }}>📋 测试日志</h3>
        <div style={{
          backgroundColor: '#2d3748',
          color: '#e2e8f0',
          padding: '15px',
          borderRadius: '8px',
          fontFamily: 'Consolas, Monaco, monospace',
          fontSize: '14px',
          maxHeight: '400px',
          overflowY: 'auto'
        }}>
          {testResults.length > 0 ? (
            testResults.map((result, index) => (
              <div key={index} style={{ marginBottom: '5px' }}>
                {result}
              </div>
            ))
          ) : (
            <div style={{ color: '#a0aec0' }}>等待测试结果...</div>
          )}
        </div>
      </div>

      {/* 使用说明 */}
      <div style={{
        marginTop: '20px',
        padding: '15px',
        backgroundColor: '#e8f4fd',
        border: '1px solid #b8daff',
        borderRadius: '8px'
      }}>
        <h4 style={{ margin: '0 0 10px 0', color: '#004085' }}>💡 使用说明</h4>
        <ul style={{ margin: 0, paddingLeft: '20px', color: '#004085' }}>
          <li>点击 "🔍 重新检测视频" 刷新视频列表</li>
          <li>点击 "🧪 测试所有文件" 检查文件可访问性</li>
          <li>所有检测到的视频都支持完整的人物检测功能</li>
          <li>如果视频没有显示，请检查文件是否在 public/videos/ 目录中</li>
          <li>确保视频文件名与代码中的列表匹配</li>
        </ul>
      </div>
    </div>
  )
}

export default VideoDetectionTest
